new Vue({
    el: '#app',
    data: {
        addresses: [],
        showModal: false,
        editMode: false,
        currentAddress: {
            id: '',
            name: '',
            phone: '',
            province: '',
            city: '',
            district: '',
            address: '',
            isDefault: false,
            countryCode: '+86'
        },
        provinces: [],
        cities: [],
        districts: [],
        orderItems: [

        ],
        selectedAddress: null,
        orderNotes: '',
        selectedIndex: -1, // 当前选中地址的索引
        // 订单编号
        orderNo: null,
        alipayForm: null,
        showCouponModal: false,
        availableCoupons: [],
        isLoadingCoupons: false,
        couponError: null,
        selectedCoupon: null,
    },
    computed: {
        rawOrderTotalAmount() {
            return this.orderItems.reduce((total, item) =>
                total + (item.commoditySalePrice * item.commodityNum), 0).toFixed(2);
        },
        orderTotalAmount() {
            let total = parseFloat(this.rawOrderTotalAmount); 

            if (this.selectedCoupon) {
                if (total >= this.selectedCoupon.couponCondition) {
                    total -= this.selectedCoupon.couponPrice;
                } else {
                    console.warn("优惠券未满足使用条件，将不应用此优惠券。");
                }
            }
            return Math.max(0, total).toFixed(2);
        }
    },
    methods: {
        // 获取用户ID
        getUserIdFromUrl() {
            return localStorage.getItem('userId');
        },

        // 获取地址列表
        fetchAddresses() {
            // const userId = this.getUserIdFromUrl();
            $.ajax({
                url: `http://localhost:8080/address/findAllAddress`,
                type: 'POST',
                dataType: 'json',
                data: { userId: localStorage.getItem('userId') },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (response) => {
                    if (response.code === 200 && Array.isArray(response.data)) {
                        this.addresses = response.data;
                        // 处理默认地址
                        let defaultAddrIndex = -1;
                        // 遍历地址列表，处理默认地址
                        let processedAddresses = response.data.map((addr, index) => {
                            this.$set(addr, 'isDefault', !!addr.isDefault);

                            // 找到第一个默认地址的索引
                            if (addr.isDefault && defaultAddrIndex === -1) {
                                defaultAddrIndex = index;
                            }
                            return addr;
                        });

                        // 在前端处理：如果后端返回多个默认地址，只保留第一个的默认状态 (基于索引)
                        if (defaultAddrIndex !== -1) {
                            processedAddresses.forEach((addr, index) => {
                                if (index !== defaultAddrIndex) {
                                    this.$set(addr, 'isDefault', false); // 取消其他默认状态
                                }
                            });
                        }
                        this.addresses = processedAddresses;
                        // 如果没有地址，则将索引设置为-1
                        if (this.addresses.length > 0) {
                            this.selectedIndex = defaultAddrIndex !== -1 ? defaultAddrIndex : 0;
                            this.selectedAddress = this.addresses[this.selectedIndex];
                        } else {
                            this.selectedIndex = -1;
                            this.selectedAddress = null;
                        }

                    } else {
                        this.addresses = [];
                        this.selectedAddress = null;
                        this.selectedIndex = -1;
                        alert('加载地址列表失败: ' + (response.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    this.addresses = [];
                }
            });
        },

        // 加载省份数据 (用于三级联动)
        loadProvinces() {
            $.ajax({
                url: "http://localhost:8080/api/province",
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (result) => {
                    this.provinces = result.list;
                }
            });
        },

        // 省份选择改变时加载城市
        onProvinceChange() {
            this.currentAddress.city = '';
            this.currentAddress.district = '';
            this.cities = [];
            this.districts = [];
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://localhost:8080/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (result) => {
                        this.cities = result.list;
                    }
                });
            }
        },

        // 城市选择改变时加载区县
        onCityChange() {
            this.currentAddress.district = '';
            this.districts = [];
            if (this.currentAddress.province && this.currentAddress.city) {
                $.ajax({
                    url: "http://localhost:8080/api/area",
                    type: 'GET',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    data: {
                        pname: this.currentAddress.province,
                        cname: this.currentAddress.city
                    },
                    success: (result) => {
                        this.districts = result.list;
                    }
                });
            }
        },

        // 打开新建地址模态框
        openNewAddress() {
            // 重置currentAddress数据
            this.currentAddress = {
                id: '',
                recipient: '',
                phone: '',
                region: '',
                detail: '',
                isDefault: false,
                province: '',
                city: '',
                district: '',
                countryCode: '+86'
            };
            this.editMode = false;
            this.showModal = true;

            // 清空城市和区县下拉框数据
            this.cities = [];
            this.districts = [];
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },

        // 打开编辑地址模态框并填充数据
        async editAddress(addr) {
            console.log('编辑地址:', addr);
            // 初始化编辑数据
            this.currentAddress = { ...addr };
            this.editMode = true; // 设置为编辑模式
            this.showModal = true;

            // 解析region字符串，填充省市区字段
            if (this.currentAddress.region) {
                const regionParts = this.currentAddress.region.split(' ');
                if (regionParts.length >= 1) this.currentAddress.province = regionParts[0];
                if (regionParts.length >= 2) this.currentAddress.city = regionParts[1];
                if (regionParts.length >= 3) this.currentAddress.district = regionParts[2];
            }
            console.log('当前地址:', this.currentAddress);

            // 根据已有的省份加载城市
            if (this.currentAddress.province) {
                $.ajax({
                    url: "http://localhost:8080/api/city",
                    type: 'GET',
                    data: { pname: this.currentAddress.province },
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (cityRes) => {
                        this.cities = cityRes.list;
                        // 根据已有的城市加载区县
                        if (this.currentAddress.city) {
                            $.ajax({
                                url: "http://localhost:8080/api/area",
                                type: 'GET',
                                data: { pname: this.currentAddress.province, cname: this.currentAddress.city },
                                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                                success: (districtRes) => {
                                    this.districts = districtRes.list;
                                }
                            });
                        } else {
                            this.districts = [];
                        }
                    }
                });
            } else {
                // 如果没有省份信息，清空城市和区县下拉框
                this.cities = [];
                this.districts = [];
            }
            // 确保省份下拉框加载了数据
            if (this.provinces.length === 0) {
                this.loadProvinces();
            }
        },
        // 保存地址
        saveAddress() {
            const url = this.editMode ? '/updateAddress' : '/addAddress';
            const method = 'POST';

            // 组织要发送到后端的数据
            const addressData = {
                ...this.currentAddress,
                region: `${this.currentAddress.province || ''} ${this.currentAddress.city || ''} ${this.currentAddress.district || ''}`.trim(),
                userId: localStorage.getItem('userId') || ''
            };

            $.ajax({
                url: "http://localhost:8080/address" + url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(addressData),
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                dataType: 'json',
                success: (res) => {
                    if (res.code === 200) {
                        alert(this.editMode ? '地址更新成功' : '新地址添加成功');
                        this.showModal = false;
                        this.fetchAddresses();
                    } else {
                        alert('操作失败：' + res.message);
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，保存失败', status, err);
                }
            });
        },

        // 获取订单详细信息，包括商品列表
        fetchOrderDetails() {
            const params = new URLSearchParams(window.location.search);
            const orderId = params.get('orderId');
            if (!orderId) {
                console.error('URL中缺少orderId参数');
                return;
            }

            $.ajax({
                url: `http://localhost:8080/order/findOrderById?orderId=${encodeURIComponent(orderId)}`,
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        this.orderItems = res.data.commodityList;
                        this.orderNo = res.data.orderId;
                        this.orderItems.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.commodityPicture[0].commodityImageUrl = 'http://localhost:8080' + product.commodityPicture[0].commodityImageUrl;
                            } else {
                                product.image = '/photo/default.jpg'; // 默认图片
                            }
                            console.log('商品图片路径:', this.orderItems)
                        });
                    } else {
                        this.orderItems = [];
                        console.error('获取订单商品失败:', res);
                        alert('获取订单商品失败: ' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    this.orderItems = [];
                    console.error(status, error);
                    alert('网络错误，获取订单商品失败');
                }
            });
        },
        // 选择地址
        selectAddress(address, index) {
            // 如果点击的已经是当前选中的地址，不做处理
            if (this.selectedIndex === index) {
                return;
            }

            // 更新选中地址的索引和对象
            this.selectedIndex = index;
            this.selectedAddress = address;

            console.log('选中地址:', address);
        },
        // 设置默认地址
        setDefaultAddress(address) {
            // 先取消所有地址的默认状态
            if (address.isDefault) {
                return;
            }
            $.ajax({
                url: 'http://localhost:8080/address/setDefault',
                type: 'POST',
                data: { id: address.id, userId: localStorage.getItem('userId') },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        alert('默认地址设置成功');
                        this.fetchAddresses(); // 重新获取地址列表
                    } else {
                        alert('设置默认地址失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，设置默认地址失败');
                    console.error(status, error);
                }
            });
        },
        // 处理默认地址选择框变化
        onDefaultAddressChange(address) {
            if (address.isDefault) {
                this.setDefaultAddress(address);
            }
        },
        // 获取可用优惠券列表
        async fetchAvailableCoupons() {
            this.isLoadingCoupons = true;
            this.couponError = null;
            try {
                const currentOrderRawTotal = this.orderItems.reduce((sum, item) =>
                        sum + (item.commoditySalePrice * item.commodityNum), 0);
                const response = await $.ajax({
                    url: 'http://localhost:8080/order/matchConditionCoupon',
                    type: 'GET',
                    dataType: 'json',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    data: { 
                        userId: localStorage.getItem('userId'),
                        amount: currentOrderRawTotal 
                    }
                });

                if (response.code === 200 && response.data) {
                    this.availableCoupons = response.data.filter(coupon => {
                        // 确保优惠券状态是可用的 (0: 未使用)
                        const isAvailable = coupon.couponStatus === 0;
                        // 确保满足满减条件
                        const meetsCondition = currentOrderRawTotal >= coupon.couponCondition;
                        return isAvailable && meetsCondition;
                    }).map(coupon => ({
                        ...coupon,
                        couponEndTime: this.formatDate(coupon.couponEndTime) // 格式化日期
                    }));
                } else {
                    throw new Error(response.message || '获取可用优惠券失败');
                }
            } catch (error) {
                console.error( error);
                this.couponError = error.message || '加载优惠券失败';
                this.availableCoupons = [];
            } finally {
                this.isLoadingCoupons = false;
            }
        },

        // 打开优惠券选择模态框
        openCouponSelectionModal() {
            this.showCouponModal = true;
            if (this.availableCoupons.length === 0 || this.couponError) {
                this.fetchAvailableCoupons();
            }
        },

        // 选择优惠券
        selectCoupon(coupon) {
            const currentOrderTotal = this.orderItems.reduce((sum, item) =>
                sum + (item.commoditySalePrice * item.commodityNum), 0);

            if (currentOrderTotal >= coupon.couponCondition) {
                this.selectedCoupon = coupon;
                this.showCouponModal = false;
                console.log(this.selectedCoupon);
            } else {
                alert(`该优惠券需满 ${coupon.couponCondition} 元可用，当前订单金额不足。`);
            }
        },

        // 不使用优惠券
        clearSelectedCoupon() {
            this.selectedCoupon = null;
            this.showCouponModal = false;
        },

        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '无限制';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return dateString;
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        },

        // 计算剩余天数
        getRemainingDays(endTime) {
            if (!endTime || endTime === '无限制') return '长期有效';

            const endDate = new Date(endTime);
            const today = new Date();
            const diffTime = endDate - today;
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

            return diffDays > 0 ? `剩余${diffDays}天` : '已过期';
        },
        // 提交订单
        submitOrder() {
            if (!this.selectedAddress) {
                alert('请选择收货地址');
                return;
            }

            if (this.orderItems.length === 0) {
                alert('订单商品为空，无法提交订单');
                return;
            }

            // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss
            const now = new Date();
            const createTime = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0');

            // 准备提交订单的数据
            const orderData = {
                addressId: this.selectedAddress.id,
                notes: this.orderNotes,
                createTime: createTime,
                items: this.orderItems.map(item => ({
                    productId: item.productId,
                    quantity: item.quantity,
                    spec1: item.spec1,
                    spec2: item.spec2
                })),
                couponId: this.selectedCoupon ? this.selectedCoupon.couponId : null,
                couponAmount: this.selectedCoupon ? this.selectedCoupon.couponPrice : 0
            };

            $.ajax({
                // 后端提交订单的接口
                url: 'http://localhost:8080/alipay/qrcode',
                type: 'POST',
                data: {
                    userId: localStorage.getItem('userId'),
                    orderNo: this.orderNo,
                    amount: this.orderTotalAmount,
                    // 优惠券ID
                    couponId: this.selectedCoupon ? this.selectedCoupon.couponId : null
                },
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        this.alipayForm = res.data; // 获取支付宝支付表单
                        console.log('支付宝表单:', this.alipayForm);
                        this.$nextTick(() => {
                            const container = document.getElementById('alipay-container');
                            const form = container.querySelector('form'); // 在容器内查找表单
                            if (form) {
                                form.submit();
                            } else {
                                console.error('找不到 <form> 元素，请检查插入的内容是否为完整 HTML 表单');
                            }
                        });

                    } else {
                        alert('提交订单失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，提交订单失败');
                    console.error(status, error);
                }
            });
        },

        // 查询支付状态
        pollPaymentStatus(orderId) {
            // 检查当前页面是否仍显示支付相关内容，如果用户已离开此页，则停止查询
            const paymentContainer = document.querySelector('.payment-container');
            if (!paymentContainer || paymentContainer.style.display === 'none') {
                console.log('用户已离开支付页面，停止轮询。');
                return;
            }
            const checkStatus = () => {
                $.ajax({
                    url: `/api/payment/status?orderId=${orderId}`,
                    type: 'GET',
                    dataType: 'json',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (res) => {
                        if (res.code === 200) {
                            if (res.data.status === 'PAID') {
                                // 支付成功，清除定时器
                                this.stopCountdown();
                                // 支付成功，跳转到订单列表页面
                                alert('支付成功！');
                                window.location.href = `order.html?orderId=${orderId}`;
                            } else if (res.data.status === 'PENDING') {
                                // 继续查询
                                setTimeout(checkStatus, 3000);
                            } else {
                                alert('支付失败：' + (res.message || '未知错误'));
                                // 支付失败，可以隐藏支付区域，或显示失败信息
                                const paymentContainer = document.querySelector('.payment-container');
                                if (paymentContainer) paymentContainer.style.display = 'none';
                                this.stopCountdown(); // 停止倒计时
                            }
                        } else {
                            console.error('查询支付状态失败:', res);
                            // 继续轮询，或者根据错误类型决定是否停止
                            setTimeout(checkStatus, 3000);
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error(status, error);
                        // 网络错误，继续轮询一段时间，或者停止
                        setTimeout(checkStatus, 3000);
                    }
                });
            };

            // 开始查询
            checkStatus();
        }
    },
    mounted() {
        this.fetchAddresses();
        this.fetchOrderDetails();
        this.loadProvinces();
    }
});